package jpave.query_interface;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.table.AbstractTableModel;
import javax.swing.JTextArea;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Color;

import java.util.Vector;

import jpave.manager.ManagerFrame;

import util.ui.MenuTreeNode;
import util.ui.UserPrompt;

public class ResultsSummaryTab extends Tab
{
	private static final long serialVersionUID = -8340849413126018332L;
	public ResultsSummaryTab ( JPaveFrame parentFrame, Tab parentTab, String [] fieldList )
	{
		super(parentFrame, parentTab);
		super.setBackground(Color.WHITE);
		colNames = fieldList;
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		setBorder( BorderFactory.createEmptyBorder(10, 10, 10, 10) );
		
		btnClearSel = new JButton("Remove Selected Results");
		btnClearSel.setEnabled(false);
		btnClearSel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) { 
				int[] selRows = table.getSelectedRows();
				
				if (selRows.length == rows.size()) clearAll();
				else {	
					for (int i = 0;  i < selRows.length;  i++) {
						String name = rows.get(selRows[i]).get(0);
						getParentFrame().menuTree.removeNode(getParentFrame().menuTree.getNodeWithName(name));
						rows.remove(selRows[i]);
						tabs.remove(selRows[i]);
					}
					table.revalidate();
				}
			}
		});
		
		btnClearAll = new JButton("Remove All Results");
		btnClearAll.setEnabled(false);
		btnClearAll.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) { 
				clearAll();
			}
		});
		
		btnHelp = new JButton("Help");
		btnHelp.setBackground(ManagerFrame.HELPCOLOR);
		btnHelp.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				UserPrompt.displayHTMLResourceHelp(getParentFrame(), "List Filtered Results", "html/viewSingleTCW/ResultsSummaryTab.html");
			}
		});
		
		JPanel buttonPanel = new JPanel();
		buttonPanel.setLayout(new BoxLayout ( buttonPanel, BoxLayout.X_AXIS ));
		buttonPanel.setBackground(Color.WHITE);
		buttonPanel.add(btnClearSel);
		buttonPanel.add(Box.createHorizontalStrut(5));
		buttonPanel.add(btnClearAll);
		buttonPanel.add(Box.createHorizontalStrut(5));
		buttonPanel.add(btnHelp); // WN - redundant with the main help buttons on these pages
		buttonPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
		
		lblTitle = new JLabel("List Filtered Results");
		Font f = lblTitle.getFont();
		lblTitle.setFont(new Font(f.getName(), f.getStyle(), f.getSize()+4));
		txtDesc = new JTextArea(
				"Remove All Results also removes them from left panel.");

		txtDesc.setFont(new Font(f.getName(), Font.PLAIN, f.getSize()));
		txtDesc.setAlignmentX(Component.LEFT_ALIGNMENT);
		txtDesc.setEditable(false);
		lblError = new JLabel("The filtered result has been closed.");
		lblError.setVisible(false);
		lblError.setForeground(Color.RED);
		
		table = new JTable();
		table.setColumnSelectionAllowed( false );
		table.setCellSelectionEnabled( false );
		table.setRowSelectionAllowed( true );
		table.setShowHorizontalLines( false );
		table.setShowVerticalLines( true );	
		table.setIntercellSpacing ( new Dimension ( 1, 0 ) );		
		rows = new Vector<Vector<String>>();
		tabs = new Vector<JPanel>();	
		table.setModel(new ResultsTableModel());
		table.getTableHeader().setBackground(Color.WHITE);
		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 1)
					btnClearSel.setEnabled(true);
				else if (e.getClickCount() == 2) {
					int row = table.getSelectedRow();
					Tab tab = (Tab)tabs.get(row);
					if (tab != null) {
						String name = rows.get(row).get(0);
						getParentFrame().menuTree.setSelectedNode(name);
						getParentFrame().tabbedPane.setSelectedTab(tab);
						lblError.setVisible(false);
					}
					else
						lblError.setVisible(true);
				}
			}
		});
		
		scroll = new JScrollPane(table);
		scroll.setBorder( null );
		scroll.setPreferredSize(java.awt.Toolkit.getDefaultToolkit().getScreenSize()); // force table to use all space
		scroll.setAlignmentX(Component.LEFT_ALIGNMENT);
		scroll.getViewport().setBackground(Color.WHITE);
		
		add(buttonPanel);
		add(Box.createVerticalStrut(20));
		add(lblTitle);
		add(txtDesc);
		add(Box.createVerticalStrut(15));
		add(lblError);
		add(scroll);
	}
	
	private void clearAll() {
		while(tabs.size()>0) {
			String name = rows.get(0).get(0);
			getParentFrame().menuTree.removeNode(getParentFrame().menuTree.getNodeWithName(name));
			rows.remove(0);
			tabs.remove(0);
		}
		table.revalidate();

		btnClearAll.setEnabled(false);
		btnClearSel.setEnabled(false);
		lblError.setVisible(false);
		
		revalidate(); repaint();
	}
	
	private String nodeToString(String parentName) {
		MenuTreeNode parentNode = getParentFrame().menuTree.getNodeWithName(parentName);
		if (parentNode == null) return null;
		
		String out = "";
		for (int i = 0;  i < parentNode.getChildCount();  i++) {
			MenuTreeNode childNode = parentNode.getChildAt(i);
			
			if (childNode.isVisible()) {
				if (out != "") out += ", ";
				out += childNode.getText();
			}
		}
		
		return out;
	}
	
	public int addBasicResultSummary(String name, Tab tab, MenuTreeNode node) {
		btnClearAll.setEnabled(true);
		lblError.setVisible(false);

		Vector<String> newRow = new Vector<String>();
		newRow.add(name);
		newRow.add(JPaveFrame.BasicContigQuery);
		for (int i = 2;  i < colNames.length;  i++) {
			newRow.add("");
		}
		rows.add(newRow);
		tabs.add(tab);
		table.revalidate();
		
		return rows.size()-1;
	}
	
	public int addResultSummary(String name, Tab tab, MenuTreeNode node) {
		btnClearAll.setEnabled(true);
		lblError.setVisible(false);
		
		//Just in case query tab is collapsed 
		MenuTreeNode parentNode = null;
		if(colNames.length >= 1) 
			parentNode = getParentFrame().menuTree.getNodeWithName(colNames[1]);
		
		boolean collapseAfter = false;
		if(parentNode != null && parentNode.getParentNode().isChildCollapsed()) {
			parentNode.getParentNode().expandChildren();
			collapseAfter = true;
		}

		Vector<String> newRow = new Vector<String>();
		newRow.add(name);
		for (int i = 1;  i < colNames.length;  i++) {
			String column = nodeToString(colNames[i]);
			newRow.add(column);
		}
		
		if(collapseAfter)
			parentNode.getParentNode().collapseChildren();
		
		rows.add(newRow);
		tabs.add(tab);
		table.revalidate();
		
		return rows.size()-1;
	}
	
	public void removeResultSummary(Tab tab) {		
		int index = tabs.indexOf(tab);
		if (index >= 0) {
			rows.remove(index);
			tabs.remove(index);
			//tabs.setElementAt(null, index);
			lblError.setVisible(false);
			table.revalidate();
		}
	}
	
	/**
	 * Tab is about to close, free the associated memory
	 */
	public void close()
	{
		table = null;
		if(rows != null) rows.clear();
		rows = null;
		if(tabs != null) tabs.clear();
		tabs = null;
	}
	
	private class ResultsTableModel extends AbstractTableModel {
		private static final long serialVersionUID = 774460555629612058L;

		public int getColumnCount() {
            return colNames.length;
        }

        public int getRowCount() {
            return rows.size();
        }
        
        public Object getValueAt(int row, int col) {
            Vector<String> r = rows.elementAt(row);
            return r.elementAt(col);
        }
        
        public String getColumnName(int col) {
            return colNames[col];
        }
	}
	
	private JTable table = null;
	private JLabel lblTitle = null;
	private JLabel lblError = null;
	private JTextArea txtDesc = null;
	private JScrollPane scroll = null;
	private JButton btnClearSel = null;
	private JButton btnClearAll = null;
	private JButton btnHelp = null;
	private String[] colNames = null;
	private Vector<Vector<String>> rows = null;
	private Vector<JPanel> tabs = null;
}

